package xyz.eden.cloud.common.core.system;

import xyz.eden.cloud.common.core.exception.SystemException;
import xyz.eden.cloud.common.core.io.file.FileUtils;
import xyz.eden.cloud.common.core.util.AssertUtils;
import xyz.eden.cloud.common.core.util.StringUtils;

import java.io.File;
import java.lang.management.ManagementFactory;

public class PidUtils {

    private static final String PID = initPid();

    public static String getPid() {
        return PID;
    }

    private static String initPid() throws RuntimeException {
        String jvmName = resolveJvmName();
        if (StringUtils.isBlank(jvmName)) {
            throw new SystemException("jvmName is blank.");
        }
        String[] split = jvmName.split("@");
        return split[0];
    }

    public static void write(File file) throws Exception {
        AssertUtils.isNotBlank(PID, new SystemException("pid is no available"));
        FileUtils.append(PID, file);
    }


    /**
     * 获取JVM名称
     *
     * @return
     */
    private static String resolveJvmName() {
        return ManagementFactory.getRuntimeMXBean().getName();
    }
}
